package com.kang.controller;

import com.kang.pojo.Address;
import com.kang.pojo.Users;
import com.kang.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author 吃三明治派对中的康康
 * @Date 2022/5/1 19:27
 * @Version 1.0
 */
@Controller
public class AddressController {

    @Autowired
    AddressService addressService;

    //跳转到添加收货信息页面
    @RequestMapping("/toAddAddress")
    public String toAddAddress(){
        return "shouhuo";
    }


    //添加地址
    @RequestMapping("/addAddress/{flag}")
    public String addAddress(Model model, Address address, HttpServletRequest request, @PathVariable int flag){
        if(address.getRealname()       != null
                && address.getMobile() != null
                && address.getZone()   != null
                && !address.getStreet().equals("")){
            Users user = (Users) request.getSession().getAttribute("UserSession");
            address.setUid(user.getUid());
            addressService.insertAddress(address);
        }else {
            model.addAttribute("addAddressError","表格不能为空！");
        }
        if(flag == 1) return "redirect:/buyShopping";
        else return "redirect:/userAddress";
    }

    //删除地址
    @RequestMapping("/deleteAddress/{aid}/{flag}")
    public String deleteAddress(@PathVariable long aid, @PathVariable int flag){
        addressService.deleteAddress(aid);
        if(flag == 1) return "redirect:/buyShopping";
        else return "redirect:/userAddress";
    }

    //携带信息跳转到修改界面的控制器
    @RequestMapping("/edit/{aid}/{flag}")
    public String toEditAddress(Model model, @PathVariable long aid, @PathVariable int flag){
        Address address = addressService.researchAddressByAid(aid);
        model.addAttribute("willEditAddress",address);
        if(flag == 1) return "editAddress";
        else return "userAddressEdit";
    }

    //修改信息
    @RequestMapping("/editAddress/{flag}")
    public String editAddress(Address address, @PathVariable int flag){
        addressService.updateAddress(address);
        if(flag == 1) return "redirect:/buyShopping";
        else return "redirect:/userAddress";
    }

    //展示信息
    @RequestMapping("/userAddress")
    public String userAddress(Model model,HttpServletRequest request){

        if(request.getSession().getAttribute("UserSession") == null) return "redirect:/toLogin";
        Users user = (Users) request.getSession().getAttribute("UserSession");
        model.addAttribute("userAddressModel",addressService.researchAddressByUid(user.getUid()));
        return "userAddress";
    }
}
